package com.yuwei.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//简易加法计算器
public class CalcExercise {
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

class Calculator extends Frame{

    //TextField  文本框类
    TextField num1 = new TextField(10);
    //Label      标签类
    Label label = new Label("+");
    TextField num2 = new TextField(10);
    Button button = new Button("=");
    TextField sum = new TextField(20);

    public void loadFrame(){
        setSize(800,100);

        //按钮的点击监听
        button.addActionListener(new MyCalculatorListener(this));

        setLayout(new FlowLayout());

        add(num1);
        add(label);
        add(num2);
        add(button);
        add(sum);

        setVisible(true);
    }

    //内部类
    class MyCalculatorListener implements ActionListener{
        Calculator calculator = null;

        public MyCalculatorListener(Calculator calculator){
            this.calculator = calculator;
        }

        @Override
        //当按钮被点击则调用此方法
        public void actionPerformed(ActionEvent e) {
            int num1 = Integer.parseInt(calculator.num1.getText());
            int num2 = Integer.parseInt(calculator.num2.getText());
            calculator.sum.setText("" + (num1+num2));
            calculator.num1.setText("");
            calculator.num2.setText("");
        }
    }
}

//class MyCalculatorListener implements ActionListener{
//    Calculator calculator = null;
//
//    public MyCalculatorListener(Calculator calculator){
//        this.calculator = calculator;
//    }
//
//    @Override
//    public void actionPerformed(ActionEvent e) {
//        int num1 = Integer.parseInt(calculator.num1.getText());
//        int num2 = Integer.parseInt(calculator.num2.getText());
//        calculator.sum.setText("" + (num1+num2));
//        calculator.num1.setText("");
//        calculator.num2.setText("");
//    }
//}
